package com.back.campus_back.service.impl;


import com.back.campus_back.domain.User;
import com.back.campus_back.mapper.UserMapper;
import com.back.campus_back.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;



import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ${author}
 * @since 2021-04-17
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private BCryptPasswordEncoder encoder;


    /*
     * 根据查询用户的id和密码查询用户是否存在，进行登录
     * */
    @Override
    public User login(String username, String password) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username",username);
        //查询一个数据
        User user = userMapper.selectOne(wrapper);
        //对密码进行对比匹配
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        //这是前段输入的密码进行加密
        String inputpwd = encoder.encode(password);
        //这是数据库已经加密的密码
        String sqlpwd=user.getPassword();
        //进行密码匹配
        boolean flag = encoder.matches(password,sqlpwd);
        if(flag){
            return user;
        }else {
            return null;
        }
    }

    /*
     * 根据电话号码查询用户是否存在，进行登录
     * */
    @Override
    public User SMSLogin(String phone) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("phone",phone);
        //查询一个数据
        User user = userMapper.selectOne(wrapper);
        if(user!=null){
            return user;
        }else {
            return null;
        }
    }

    /*
     * 根据用户名查询
     * */
    @Override
    public User findUserName(String username) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username",username);
        //查询一个数据
        User user = userMapper.selectOne(wrapper);
        if(user!=null){
            return user;
        }else {
            return null;
        }
    }

    /*
     * 查询全部用户
     * */
    @Override
    public List<User> findAllUser( ){
        List<User> userlist = userMapper.selectList(null);
        return userlist;
    }

    /*
     * 查询全部用户：模糊查询
     * */
    @Override
    public IPage<User> findAllUser(Integer current, Integer size,String username){
        //参数1：当前页
        //参数二：页面大小
        //使用分页插件和，所以分页插件也变得简单

        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("create_time");

        wrapper.like("username",username);

        Page<User> page = new Page<>(current, size);
        IPage<User> userIPage = userMapper.selectPage(page, wrapper);

        return userIPage;

    }

    //分页查询
    @Override
    public IPage<User> findByUser(Integer current, Integer size) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("create_time");

        Page<User> page = new Page<>(current,size);
        IPage<User> userIPage = userMapper.selectPage(page,wrapper);
        return userIPage;
    }


    /*
     * 根据id查询用户
     * */
    @Override
    public User findUserById(Integer user_id) {
        User user=null;
        //先从redis缓存中查询数据
        Object o = redisTemplate.opsForValue().get(user_id);
        //查询不为空，说明缓存有数据，那就直接返回
        if(o!=null){
            user=(User) o;
        }else{
            //反之，说明缓存无中此数据，那就去数据查询
            QueryWrapper<User> wrapper = new QueryWrapper<>();
            wrapper.eq("user_id",user_id);
            //查询一个数据
            user=userMapper.selectOne(wrapper);
            if (user !=null){
                //数据库查询到不为空，就将数据加到redis缓存中,设置有效期2天
                redisTemplate.opsForValue().set(user_id,user,2, TimeUnit.DAYS);

            }else {
                return null;
            }
        }
        return user;
    }

    /*
     * 注册用户操作：
     * 获取前端发来的用户名和密码进行注册
     * */
    @Override
    public String registerUser(String userName,String password){
        User user=new User();
        user.setUsername(userName);
        //进行加密密码
        user.setPassword(encoder.encode(password));
        int result = userMapper.insert(user);
        if(result == 1){
            return "success";
        }else{
            return "error";
        }
    }


    /*
     * 更新用户信息
     * */
    @Override
    public User updateUserInfo(User user){
            System.out.println("user:"+user);
            int result = userMapper.updateById(user);
            int user_id= user.getUserId();
            //更新缓存信息
            redisTemplate.opsForValue().set(user_id,user);
            if(result == 1){
                return user;
            }else{
                return null;
            }
    }


    /*
     * 更新用户信息
     * */
    @Override
    public User uploadImg(String ImgName,Integer userId){
        UpdateWrapper<User> userUpdateWrapper=new UpdateWrapper<>();
        userUpdateWrapper.eq("user_id",userId).set("head_pic",ImgName);//UPDATE user SET head_pic=? WHERE user_id = ?
        User user=new User();
        user.setHeadPic(ImgName);
        int result= userMapper.update(user,userUpdateWrapper);
        if(result == 1){
            user= userMapper.selectById(userId);
            return user;
        }else{
            return null;
        }
    }


    /*
     * 根据id删除用户
     * */
    @Override
    public String deleteUserById(Integer user_id) {
        int result = userMapper.deleteById(user_id);
        redisTemplate.delete(user_id);
        if(result == 1){
            return "de_success";
        }else{
            return "de_error";
        }
    }

}
